<template>
  <div id="single-image-upload">
    <el-upload ref="upload" name="singleFile" :action="uploadAction" list-type="picture-card"
      :on-success="handleSuccess" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList"
      :limit="1"><i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogPreviewVisible" :modal="false">
      <img width="100%" :src="fullUrl(value)" alt />
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "SingleImageUpload",
    props: {
      value: String
    },
    data() {
      return {       
        dialogPreviewVisible: false,
        uploadAction: this.fullUrl("/upload/single"),
        uploadBtn: undefined,
        fileList: [], //用于图片回显
      };
    },
    mounted() {
      //获取文件上传按钮的DOM元素，每个上传组件有且仅有1个
      this.uploadBtn = this.$refs.upload.$el.getElementsByClassName("el-upload")[0];
      this.handleValueChanged(this.value);

    },
    watch:{
      value(newValue){
        this.handleValueChanged(newValue);
      }
    },

    methods: {
      handleValueChanged(value){
        if(this.value){
          this.fileList = [{
            url: this.fullUrl(this.value)
          }]; //用于图片回显
          this.uploadBtn.style.display = "none";
        }else{
          this.fileList = []; //用于图片回显
          this.uploadBtn.style.display = "inline-block";
        }
      },
      fullUrl(url) {
        return `${this.BaseAPI}${url}`;
      },

      //图片上传成功 result是接口返回数据{code msg ,url}
      handleSuccess(result) {
        let imageUrl = result.url;
        this.fileList = [{
          url: this.fullUrl(imageUrl)
        }];

        //不显示上传按钮
        this.uploadBtn.style.display = "none";
        //向父组件传递参数：imageUrl的值（不含域名）        
        this.$emit("update:value", imageUrl);
      },

      //移除图片
      handleRemove() {
        let imageUrl = "";
        this.fileList = [];

        //显示上传按钮
        this.uploadBtn.style.display = "inline-block";
        //向父组件传递参数：imageUrl的值（不含域名）        
        this.$emit("update:value", imageUrl);
      },

      //文件上传之前调用做一些拦截限制
      beforeUpload(file) {
        const isJPGPNG =
          file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPGPNG) {
          this.$message.error("上传图片只能是 JPG/PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 2MB!");
        }
        return isJPGPNG && isLt2M;
      },

      //预览图片时调用
      handlePreview() {
        this.dialogPreviewVisible = true;
      },
    },
  };
</script>

<style lang="less" scoped>
</style>
